﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Picdownload
{
    // 用于将url重新组合后再加到键树中
    // 如http://www.comprg.com.cn和http://www.comprg.com.cn/是一样的
    // 因此，它们的hashcode也要求一样
    class UrlFilter
    {
        public static KeyTree urlHashCode = new KeyTree();
        private static object syncUrlHashCode = new object();
        private static string processUrl(string url) // 重新组合Url
        {
            try
            {
                Uri uri = new Uri(url);
                string s = uri.PathAndQuery;
                if (s.Equals("/"))
                    s = "";
                return uri.Host + s;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private static bool exists(string url) // 判断url是否存在
        {
            try
            {
                lock (syncUrlHashCode)
                {
                    url = processUrl(url);
                    return urlHashCode.exists((uint)url.GetHashCode());
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static bool isOK(string url)
        {
            return !exists(url);
        }
        // 加处理完的Url加到键树中
        public static void addUrl(string url)
        {
            try
            {
                lock (syncUrlHashCode)
                {
                    url = processUrl(url);
                    urlHashCode.add((uint)url.GetHashCode());
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

    }
}
